package top.mcwebsite.lib.router.plugin

import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.commons.AdviceAdapter

class RouteBuilderInjectMethodVisitor(
    methodVisitor: MethodVisitor,
    private val routeBuilderNames: Set<String>,
    access: Int,
    name: String?,
    descriptor: String?
) : AdviceAdapter(Opcodes.ASM9, methodVisitor, access, name, descriptor) {
    override fun onMethodExit(opcode: Int) {
        super.onMethodExit(opcode)
        routeBuilderNames.forEach { moduleName ->
            println("inject method moduleName = $moduleName")
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            // 调用路由构建器方法
            mv.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                Constant.ROUTER_BUILDER_PREFIX + moduleName + "Kt",
                Constant.ROUTER_BUILDER_METHOD_PREFIX + moduleName,
                "(Landroidx/navigation/NavGraphBuilder;)V",
                false
            )
        }
    }
}